package controllers

import (
	"Myshop/models"
	"encoding/base64"
	"github.com/gomodule/redigo/redis"
	"math"

	//"github.com/beego/beego/v2/client/orm"
	"github.com/astaxie/beego/orm"
	//"github.com/beego/beego/v2/core/utils"
	"github.com/astaxie/beego/utils"
	//beego "github.com/beego/beego/v2/server/web"
	"github.com/astaxie/beego"
	beelog "github.com/astaxie/beego/logs"
	"regexp"
	"strconv"
)

func GetUserName(this *beego.Controller) string {
	username := this.GetSession("userName")
	if username == nil {
		this.Data["username"] = ""
	} else {
		this.Data["username"] = username.(string)
		return username.(string)
	}
	return ""
}

type UserCon struct {
	beego.Controller
}

func (this *UserCon) ShowRegister() {
	this.TplName = "register.html"
}
func (this *UserCon) PostRegister() {
	//1、获取数据
	name := this.GetString("user_name")
	pwd := this.GetString("pwd")
	cpwd := this.GetString("cpwd")
	email := this.GetString("email")

	//2、校验数据
	if name == "" || pwd == "" || cpwd == "" || email == "" {
		this.Data["errmsg"] = "数据不完整，重新输入"
		this.TplName = "register.html"
		return
	}
	if pwd != cpwd {
		this.Data["errmsg"] = "两次密码不一致"
		this.TplName = "register.html"
		return
	}
	re, err := regexp.Compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")
	res := re.FindString(email)
	if res == "" {
		this.Data["errmsg"] = "邮箱格式不正确"
		this.TplName = "register.html"
		return
	}

	//3、处理数据
	o := orm.NewOrm()
	var user models.User
	user.Name = name
	user.PassWord = pwd
	user.Email = email
	_, err = o.Insert(&user)
	if err != nil {
		this.Data["errmsg"] = "注册失败"
		return
	}

	//邮箱激活
	emailConfig := `{"username":"405910024@qq.com","password":"hlxjqdcgobejcbdf","host":"smtp.qq.com","port":587}`
	emailConn := utils.NewEMail(emailConfig)
	emailConn.From = "405910024@qq.com"
	emailConn.To = []string{email}
	emailConn.Subject = "天天生鲜用户注册"
	// 注意：我们这里发送给用户的是激活请求地址（公网地址和端口号）
	emailConn.Text = "localhost:8080/active?id=" + strconv.Itoa(user.Id)
	emailConn.Send()

	//4、转向
	this.Ctx.WriteString("请前往邮箱激活！")
	//this.Ctx.Output([]byte("请前往邮箱激活！"))

}
func (this *UserCon) ActiveMail() {
	id, err := this.GetInt("id")
	if err != nil {
		this.Data["errmsg"] = "激活失败"
		this.TplName = "register.html"
		return
	}
	var user models.User
	user.Id = id
	o := orm.NewOrm()
	err = o.Read(&user)
	if err != nil {
		this.Data["errmsg"] = "激活的用户不存在"
	}
	user.Active = true
	o.Update(&user)
	this.Redirect("/login", 302)
}

func (this *UserCon) GetLogin() {
	username := this.Ctx.GetCookie("username")
	temp, err := base64.StdEncoding.DecodeString(username)
	if err != nil {
		this.Data["checked"] = ""
	} else {
		this.Data["checked"] = "checked"
		this.Data["username"] = string(temp)
	}
	this.TplName = "login.html"
}
func (this *UserCon) PostLogin() {
	check := this.GetString("remember")
	username := this.GetString("username")
	pwd := this.GetString("pwd")

	if username == "" || pwd == "" {
		this.Data["errmsg"] = "信息不全！"
		this.TplName = "login.html"
		return
	}

	o := orm.NewOrm()
	var user models.User
	user.Name = username
	err := o.Read(&user, "Name")
	if err != nil {
		this.Data["errmsg"] = "账号或者密码错误！"
		beelog.Info("账号错误！")
		this.TplName = "login.html"
		return
	}
	if user.PassWord != pwd {
		this.Data["errmsg"] = "账号或者密码错误！"
		beelog.Info("密码错误！")
		this.TplName = "login.html"
		return
	}

	if check == "on" {
		temp := base64.StdEncoding.EncodeToString([]byte(username))
		this.Ctx.SetCookie("username", temp, 24*3600*7)
	} else {
		this.Ctx.SetCookie("username", username, -1)
	}
	this.SetSession("userName", username)
	beelog.Info(this.GetSession("userName"))
	this.Redirect("/user/home", 302)
}

func (this *UserCon) GetInfo() {
	username := GetUserName(&this.Controller)
	this.Data["username"] = username
	o := orm.NewOrm()
	//---
	var addr models.Address
	o.QueryTable("Address").RelatedSel("User").Filter("User__Name", username).Filter("Isdefault", true).All(&addr)
	if addr.Id == 0 {
		this.Data["addr"] = ""
	} else {
		this.Data["addr"] = addr
	}

	conn, err := redis.Dial("tcp", ":6379")
	defer conn.Close()
	if err != nil {
		beego.Error("redis链接出错！")
	}
	//获取用户ID
	var user models.User
	user.Name = username
	o.Read(&user, "Name")
	rep, err := conn.Do("lrange", "history_"+strconv.Itoa(user.Id), 0, 4)
	//回复助手函数
	goodsIDs, _ := redis.Ints(rep, err)
	var goodsSKUs []models.GoodsSKU
	for _, value := range goodsIDs {
		var goods models.GoodsSKU
		goods.Id = value
		o.Read(&goods)
		goodsSKUs = append(goodsSKUs, goods)
	}

	this.Data["goodsSKUs"] = goodsSKUs
	//---
	this.Data["username"] = username
	this.Data["phone"] = addr.Phone

	this.Layout = "userCenterLayout.html"
	this.TplName = "user_center_info.html"
}
func (this *UserCon) GetOrder() {
	username := GetUserName(&this.Controller)
	page, _ := this.GetInt("pageIndex")

	o := orm.NewOrm()
	var user models.User
	user.Name = username
	o.Read(&user, "Name")

	var orderInfo []models.OrderInfo

	pageSize := 2

	count, _ := o.QueryTable("OrderInfo").Filter("User__Id", user.Id).Count()
	pageCount := int(math.Ceil(float64(count) / float64(pageSize)))
	if page < 1 || page > pageCount {
		page = 1
	}
	start := (page - 1) * pageSize

	//显示的页，数组
	pageN := PageTool(pageCount, page)

	prePage := page - 1
	if prePage <= 1 {
		prePage = 1
	}
	nextPage := page + 1
	if nextPage >= (pageCount) {
		nextPage = pageCount
	}

	o.QueryTable("OrderInfo").Filter("User__Id", user.Id).Limit(pageSize, start).OrderBy("-Id").All(&orderInfo)
	goodsBuffer := make([]map[string]interface{}, len(orderInfo))

	for index, val := range orderInfo {

		var orderGoods []models.OrderGoods
		o.QueryTable("OrderGoods").RelatedSel("OrderInfo", "GoodsSKU").Filter("OrderInfo__Id", val.Id).All(&orderGoods)

		tmp := make(map[string]interface{})
		tmp["orderGoods"] = orderGoods
		tmp["orderInfo"] = val

		goodsBuffer[index] = tmp
	}

	this.Data["pages"] = pageN
	this.Data["prePage"] = prePage
	this.Data["nextPage"] = nextPage

	this.Data["goodsBuffer"] = goodsBuffer
	this.Data["username"] = username
	this.Layout = "userCenterLayout.html"
	this.TplName = "user_center_order.html"
}
func (this *UserCon) GetSite() {
	username := GetUserName(&this.Controller)
	o := orm.NewOrm()
	var addr models.Address
	//关联查询
	o.QueryTable("Address").RelatedSel("User").Filter("User__Name", username).Filter("Isdefault", true).All(&addr)
	if addr.Id == 0 {
		this.Data["addr"] = ""
	} else {
		this.Data["addr"] = addr
	}
	this.Data["username"] = username
	this.Layout = "userCenterLayout.html"
	this.TplName = "user_center_site.html"
}
func (this *UserCon) PostSite() {
	//获取数据
	username := GetUserName(&this.Controller)
	this.Data["username"] = username
	receiver := this.GetString("receiver")
	addr := this.GetString("addr")
	zipcode := this.GetString("zipcode")
	phone := this.GetString("phone")

	//校验数据
	if phone == "" || zipcode == "" || addr == "" || receiver == "" {
		beelog.Info("数据不全，重新填写！")
		this.Redirect("/user/userCenterSite", 302)
		return
	}
	if username == "" {
		beelog.Info("您还没登陆，请登陆！")
		this.Redirect("/login", 302)
		return
	}

	//处理数据
	o := orm.NewOrm()
	var address models.Address
	address.Isdefault = true
	err := o.Read(&address, "Isdefault")
	if err == nil {
		address.Isdefault = false
		o.Update(&address)
	}

	var user models.User
	user.Name = username
	o.Read(&user, "Name")

	var addressNew models.Address
	addressNew.Isdefault = true
	addressNew.User = &user
	addressNew.Receiver = receiver
	addressNew.Phone = phone
	addressNew.Addr = addr
	o.Insert(&addressNew)
	//返回视图
	this.Redirect("/user/userCenterSite", 302)
}
func (this *UserCon) LogOut() {
	username := GetUserName(&this.Controller)
	this.Data["username"] = username
	this.DelSession("username")
	this.Redirect("/login", 302)
}
